package com.bowlong.third.payment.xiaomi;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.bowlong.lang.NumEx;
import com.bowlong.net.http.HttpParser;
import com.bowlong.util.MapEx;
import com.bowlong.util.Ref;

// 小米充值回调
public class PaymentXiaoMi {

	static final String FAIL = "{\"errcode\":\"0\",\"errMsg\":\"接收失败\"}";
	static final String SUCC = "{\"errcode\":\"200\",\"errMsg\":\"接收成功\"}";

	/*
	 * GET /paymi?appId=5715&cpOrderId=74&cpUserInfo=%E5%BB%96%E5%BD%A4&orderId=
	 * 21135953995611300550
	 * &orderStatus=TRADE_SUCCESS&payFee=100&payTime=2013-01-
	 * 30+18%3A05%3A47&productCode
	 * =01&productCount=100&productName=%E9%87%91%E5%B8
	 * %81&uid=294586&signature=83c349139fce4c744401fb9a41b69d68e454fbf6
	 * HTTP/1.1
	 */
	public static boolean checkOrder(String body, Ref<Double> money,
			Ref<Integer> orderId, Ref<String> errMsg, Ref<String> retToChannel) throws IOException {
		if(body == null || body.isEmpty()){
			retToChannel.val = FAIL;
			errMsg.val = "body == null || body.isEmpty()";
			return false;
		}

		Map<String, List<String>> map = HttpParser.parseQueryString(body,
				"UTF-8");
		if (map == null || map.isEmpty()) {
			retToChannel.val = FAIL;
			errMsg.val = "body parse error";
			return false;
		}
		double payFee = NumEx.stringToDouble((String) MapEx.getList(map,
				"payFee").get(0));
		double amount = payFee / 100;
		
		int billno = NumEx.stringToInt((String) MapEx.getList(map, "cpOrderId")
				.get(0));
		String status = (String) MapEx.getList(map, "orderStatus").get(0);

		if (status.equals("TRADE_SUCCESS")) { // 支付状态:0=失败,1=成功
			money.val = amount;
			orderId.val = billno;
			retToChannel.val = SUCC;
			errMsg.val = "status: " + status + " is ok";
			return true;
		} else {
			money.val = amount;
			orderId.val = billno;
			retToChannel.val = SUCC;
			errMsg.val = "status: " + status + " is false";
			return false;
		}
	}
}
